package com.sky.roleview.util;

import android.app.Activity;
import android.os.Handler;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.activity.R;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.reflect.TypeToken;
import com.sky.roleview.entity.RoleSkinInfo;
import com.sky.roleview.weight.PlayImageView;
//import com.master.component.user.UserManager;
//import com.master.component.user.entity.RoleSkinInfo;
//import com.master.component.utils.*;
//import com.master.component.utils.StringUtils;
//import com.smartcity.common.baserx.RxManager;
//import com.smartcity.common.commonutils.*;
//import com.smartcity.common.commonutils.UiUtils;
//import com.smartcity.smartmaster.R;
//import com.smartcity.smartmaster.app.AppApplication;
//import com.smartcity.smartmaster.app.AppConstant;
//import com.smartcity.smartmaster.widget.PlayImageView;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/9/8.
 */

public class GifEventUtils implements PlayImageView.OnClickPlayLictener {
    private static final String TAG = "GifEventUtils";
    private Activity activity;
    private PlayImageView workSexIcon;
    private ImageView iv_icon_bg;
    private LinearLayout llAddMemo;
    private TextView tvAddWork;
    private final String DOWNLOAD_PATH = "/storage/emulated/0/Download/GameGif";
//    private final SharedPreferencesUtils sharedPreferencesUtils;
    private OnCutListener listener;
//    private RxManager mRxManager;
    private int iconTop;
    private int type = -1;//-1轮播gif  0点击头部  1点击身体  2点击脚
    private boolean isplay;//是否正在循环播放
    private boolean isflag;//控制是否能自动播放
    private int position = 0;
    private int playPosition = 0;
    private List<String> roleLists = new ArrayList<>();
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            position++;
            if (position > roleLists.size() - 1) {
                position = 0;
            }
            setGif();
            handler.postDelayed(runnable, 3000);
        }
    };

    /*
     * dragImg 右下角的Imageview
     * workSexIcon 右上角的Imageview
     * iv_icon_bg  中间的Imageview
     * */
    public GifEventUtils(Activity activity, PlayImageView workSexIcon, ImageView iv_icon_bg, LinearLayout llAddMemo
            , TextView tvAddWork, OnCutListener listener) {
        this.activity = activity;
        this.workSexIcon = workSexIcon;
        this.iv_icon_bg = iv_icon_bg;
        this.llAddMemo = llAddMemo;
        this.tvAddWork = tvAddWork;
//        sharedPreferencesUtils = SharedPreferencesUtils.getInstance(AppApplication.getAppactivity(), AppConstant.SHARE_USER);
        this.listener = listener;
//        this.mRxManager = mRxManager;
        this.workSexIcon.setLisnterner(this);
    }

    /*
     * 设置Gif
     * */
    private void setGif() {
        new Thread() {
            @Override
            public void run() {
                ((Activity) activity).runOnUiThread(() -> {
//                    if (TextUtils.isEmpty(UserManager.getInstance().getUserId())) {
//                        return;
//                    }
//                    RoleSkinInfo roleSkin = UserManager.getInstance().getRoleSkin(Integer.parseInt(UserManager.getInstance().getUserId()));
                    int roleIndex = 1;
                    String json = JsonUtils.getJson(activity, "gif.json");
                    List<RoleSkinInfo> skinList = JsonUtils.jsonToT(json, new TypeToken<List<RoleSkinInfo>>() {
                    }.getType());

                    RoleSkinInfo skinBean = skinList.get(roleIndex);
                    if (null != skinBean) {
                        //得到各个部位的gif集合
                        List<String> idles = skinBean.getIdle();
                        List<String> heads = skinBean.getHead();
                        List<String> bodys = skinBean.getBody();
                        List<String> foots = skinBean.getFoot();

                        roleLists.clear();
                        switch (type) {
                            case -1://正常轮播数据
                                roleLists.addAll(idles);
                                break;
                            case 0://点击头部数据
                                roleLists.addAll(heads);
                                break;
                            case 1://点击身体数据
                                roleLists.addAll(bodys);
                                break;
                            case 2://点击脚数据
                                roleLists.addAll(foots);
                                break;
                        }


                        if (!isplay) {
                            int gifWidth = skinBean.getGifWidth();
                            int startX = skinBean.getStartX();
                            int iconWidth = skinBean.getIconWidth();
                            int iconHeight = skinBean.getIconHeight();
                            int gifHeight = skinBean.getGifHeight();
                            int bottomY = skinBean.getBottomY();
                            int startY = skinBean.getStartY();


                            //刚打开页面进入的时候这里 的宽度为0
                            int addWorkWidth = tvAddWork.getWidth();
                            if (addWorkWidth == 0) {
                                tvAddWork.measure(0, 0);
                                addWorkWidth = tvAddWork.getMeasuredWidth();
                            }


                            int addworkmargin = iconWidth / 2 - addWorkWidth / 2 + startX;
                            //角色的大小  <  添加日程的大小
                            if (gifWidth < addWorkWidth) {
                                RoleSkinInfo bean = skinList.get(0);
                                gifWidth = bean.getGifWidth();
                                gifHeight = bean.getGifHeight();
                                bottomY = bean.getBottomY();
                                startX = bean.getStartX();
                                iconWidth = bean.getIconWidth();
                                startY = skinBean.getStartY();
                                addworkmargin = iconWidth / 2 - addWorkWidth / 2 + startX;
                            }

                            //设置角色大小宽高
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) workSexIcon.getLayoutParams();
                            layoutParams.width = gifWidth;
                            layoutParams.height = gifHeight;
                            workSexIcon.setLayoutParams(layoutParams);
                            RelativeLayout.LayoutParams layoutParams_center = (RelativeLayout.LayoutParams) iv_icon_bg.getLayoutParams();
                            layoutParams_center.width = gifWidth;
                            layoutParams_center.height = gifHeight;
                            iv_icon_bg.setLayoutParams(layoutParams_center);

                            //设置角色边距
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llAddMemo.getLayoutParams();
                            int gifMarginEnd = 34;
                            int gifOffset = skinBean.getGifWidth() - skinBean.getIconWidth() - skinBean.getStartX();
                            params.setMarginEnd(-gifOffset + gifMarginEnd);
                            //屏幕中心点位合同gif中心点重合后 上移y50
                            params.topMargin = (int) ((UiUtils.getScreenHeight() - gifHeight) / 2) - 40;
                            llAddMemo.setLayoutParams(params);

                            //设置添加日程四个字的边距
                            LinearLayout.LayoutParams addWorkParams = (LinearLayout.LayoutParams) tvAddWork.getLayoutParams();
                            addWorkParams.setMarginStart(addworkmargin);
                            int topMargin = -(gifHeight - bottomY) + 12;
                            addWorkParams.topMargin = topMargin;
                            tvAddWork.setLayoutParams(addWorkParams);
                            iconTop = startY;
                        }
                        //切换右下角的icon
                        loadIcon(roleIndex);
                        //切换中间和右上角的Gif
                        if (position > roleLists.size() - 1) {
                            position = 0;
                        }
                        workSexIcon.setData(iconTop, skinBean);
                        if (type == -1) {
                            setGifData(roleIndex, roleLists.get(position));
                        } else {
                            if (playPosition > roleLists.size() - 1) {
                                playPosition = 0;
                            }
                            setGifData(roleIndex, roleLists.get(playPosition));
                        }

                    }
                });
            }
        }.start();

    }

    private void loadIcon(int roleIndex) {
/*        if (roleIndex == 0) {
            //女
            dragImg.setImageResource(R.drawable.btn_fanzhuan_girl);//右下角
        } else if (roleIndex == 1) {
            //男
            dragImg.setImageResource(R.drawable.btn_fanzhuan_boy);
        } else {
            //其他角色
            Glide.with(AppApplication.getAppactivity()).load(DOWNLOAD_PATH + (roleIndex + 1) + "/btn_gzt_fz.png")
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                    .into(dragImg);
        }*/
        //切换角色后的刷新回调
        if (listener != null) {
            listener.onRefresh();
        }
    }

    private void setGifData(int roleIndex, String assetName) {
        String result = null;
        if (roleIndex == 0) {
            result = "file:///android_asset/" + assetName;
            if (!isHaveAllFile()) {
                //女小白
//                UserManager.getInstance().updateSkinStatus("roleSelected", 0);
            }
        } else if (roleIndex == 1) {
            result = "file:///android_asset/" + assetName;
            if (!isHaveAllFile()) {
                //男小白
//                UserManager.getInstance().updateSkinStatus("roleSelected", 1);
            }
        } else {
            //判断该角色是否存在
            if (isHaveFile(roleIndex, assetName)) {
                result = "/storage/emulated/0/Download/GameGif" + (roleIndex + 1) + "/" + assetName;
            } else {
                //恢复成默认的女小白
//                sharedPreferencesUtils.put(AppConstant.MY_SEX, "0");
//                UserManager.getInstance().updateSkinStatus("roleSelected", 0);
                position = 0;
                setGif();
                return;
            }
        }
        loadOneTimeGif(activity, result, workSexIcon);

       /* Glide.with(AppApplication.getAppactivity()).load(result)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                .into(workSexIcon);*/
        Glide.with(activity).load(result)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                .into(iv_icon_bg);
/*        if (roleLists.size() > 1) {
            if (isplay == false) {
                if (type == -1) {
                    handler.postDelayed(runnable, 3000);
                    isplay = true;
                } else {
                    position++;
                }
            }
        } else if (roleLists.size() == 0) {
            stopPlay();
        }*/
    }


    /*
     * 是否存在该角色
     * */
    private boolean isHaveFile(int roleIndex, String assetName) {
        if (isplay) {
            return true;
        }
        boolean result = false;
        try {
            File gifFile = new File("/storage/emulated/0/Download/GameGif" + (roleIndex + 1) + "/" + assetName);
            if (gifFile.exists()) {
                result = true;
            } else {
                result = false;
//                RoleSkinInfo roleSkin = UserManager.getInstance().getRoleSkin(Integer.parseInt(UserManager.getInstance().getUserId()));
                String downloadStatus = "";
                String[] array = downloadStatus.split(",");
                array[roleIndex] = "0";
//                UserManager.getInstance().updateDownloadStatus("downloadStatus", StringUtils.downloadStatus(array));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
     * 是否存在所有角色的文件夹
     * */
    private boolean isHaveAllFile() {
        if (isplay) {
            return true;
        }
        boolean result = false;
        try {
            File gifFile = new File("/storage/emulated/0/Download");
            if (gifFile.exists() && gifFile.isDirectory()) {
                result = true;
            } else {
                result = false;
//                UserManager.getInstance().updateDownloadStatus("downloadStatus", com.master.component.utils.StringUtils.downloadStr());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
     * 点击角色的某个部位（头，身体，脚）
     * */
    @Override
    public void onClick(int type) {
        this.type = type;
        isplay = false;
        isflag = false;
        position = 0;
        setGif();
    }

    public interface OnCutListener {
        void onRefresh();//切换角色的监听
    }

    /*
     * 开始播放
     * */
    public void startPlay() {
        position = 0;
        type = -1;
        isplay = false;
        isflag = true;
        setGif();
    }

    /*
     * 停止播放
     * */
    public void stopPlay() {
        isplay = false;
        isflag = false;
       /* if (runnable != null) {
            handler.removeCallbacks(runnable);
        }*/
    }


    /*
     * 播放gif
     * */
    private void loadOneTimeGif(Activity activity, Object model, final ImageView imageView) {
        if (activity != null) {
            try {
                Glide.with(activity).asGif().load(model).listener(new RequestListener<GifDrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                        try {
                            Field gifStateField = GifDrawable.class.getDeclaredField("state");
                            gifStateField.setAccessible(true);
                            Class gifStateClass = Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable$GifState");
                            Field gifFrameLoaderField = gifStateClass.getDeclaredField("frameLoader");
                            gifFrameLoaderField.setAccessible(true);
                            Class gifFrameLoaderClass = Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader");
                            Field gifDecoderField = gifFrameLoaderClass.getDeclaredField("gifDecoder");
                            gifDecoderField.setAccessible(true);
                            Class gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder");
                            Object gifDecoder = gifDecoderField.get(gifFrameLoaderField.get(gifStateField.get(resource)));
                            Method getDelayMethod = gifDecoderClass.getDeclaredMethod("getDelay", int.class);
                            getDelayMethod.setAccessible(true);
                            //设置只播放一次
                            resource.setLoopCount(1);
                            //获得总帧数
                            int count = resource.getFrameCount();
                            int delay = 0;
                            for (int i = 0; i < count; i++) {
                                //计算每一帧所需要的时间进行累加
                                delay += (int) getDelayMethod.invoke(gifDecoder, i);
                            }
                            imageView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //代表自动轮播
                                    if (isflag && type == -1) {
                                        isplay = false;
                                        setGif();
                                        position++;
                                    }

                                    //代表点击头部，身体，或者脚
                                    if (isflag == false && type != -1) {
                                        //只播放一次后就恢复成自动播放状态
                                        playPosition++;
                                        type = -1;
                                        isflag = true;
                                        isplay = false;
                                    }
                                }
                            }, delay);
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }
                }).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
